import { Controller, Inject, Post, Body } from '@midwayjs/decorator';
import { Context } from '@midwayjs/koa';
import { UserService } from '../service/user.service';
import { LoginType } from '../interface/user.interface';
import { UserNotFound } from '../error/custom.error';
import { checkEssentialParams, md5, timerSync } from '../utils';

@Controller('/burst')
export class UserController {
  @Inject()
  ctx: Context;

  @Inject()
  userService: UserService;

  @Post('/normal')
  async dangerousLogin(@Body() { username, password }: LoginType) {
    checkEssentialParams(username, password);
    const target = await this.userService.findUser(username, null, () => {
      throw new UserNotFound();
    });
    if (md5(password) !== target.password) {
      return { error: 'Unauthorized' };
    }
    return {
      token: await this.userService.generateToken(username),
      username: target.username,
      avatar: target.avatar,
      background: target.background,
    };
  }

  @Post('/delay')
  async delayLogin(@Body() { username, password }: LoginType) {
    await timerSync(2000);
    return await this.dangerousLogin({ username, password });
  }
}
